package com.medical.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.medical.dao.CollectMapper;
import com.medical.dao.CourseEvaluateMapper;
import com.medical.dao.CourseOrderMapper;
import com.medical.dao.CourseSeeingMapper;
import com.medical.dao.CourseSimpleMapper;
import com.medical.dao.EnterpriseMapper;
import com.medical.dao.LanguageMapper;
import com.medical.dao.TeacherAuthenticationMapper;
import com.medical.dao.UserMapper;
import com.medical.entity.Collect;
import com.medical.entity.CourseOrder;
import com.medical.entity.CourseSeeing;
import com.medical.entity.CourseSimple;
import com.medical.entity.Enterprise;
import com.medical.entity.Language;
import com.medical.entity.MyException;
import com.medical.entity.ResultBean;
import com.medical.entity.TeacherAuthentication;
import com.medical.entity.User;
import com.medical.service.CourseSeeingService;
import com.medical.util.DataUtil;

@Service
@Transactional
public class CourseSeeingServiceImpl implements CourseSeeingService {
	@Resource
	private CourseSeeingMapper dao;
	
	@Resource
	private CourseSimpleMapper csDao;
	
	@Resource
	private CourseEvaluateMapper tDao;
	
	@Resource
	private CollectMapper cDao;
	
	@Resource
	private CourseOrderMapper oDao;
	
	@Resource
	private LanguageMapper lDao;
	
	@Resource
	private UserMapper uDao;
	
	@Resource
	private TeacherAuthenticationMapper teDao;
	
	@Resource
	private EnterpriseMapper eDao;
	
	@Override
	public ResultBean<Integer> addCourseSeeing(CourseSeeing cs, String simple) {
		// TODO Auto-generated method stub
		try {
			TeacherAuthentication ta=teDao.getByUserid(cs.getUserid());
			if(ta==null) {
				return new ResultBean<>(new MyException("未认证"));
			}
			if(ta.getStates()!=2) {
				return new ResultBean<>(new MyException("认证未通过"));
			}
			/*int num=eDao.selectCount(new EntityWrapper<Enterprise>().eq("userid", cs.getUserid()).and().eq("states", 2));
			if(num<1) {
				return new ResultBean<>(new MyException("未认证企业"));
			}*/
			cs.setTime(new Date());
			cs.setStates(1);
			cs.setRelease(true);
			cs.setBuystates(false);
			int count=dao.insert(cs);
			if(count>0) {
				if(simple!=null&&!simple.equals("")) {
					String[] data=simple.split(",");
					for(String da:data) {
						int id=Integer.parseInt(da);
						csDao.updateAuthenticationid(cs.getId(), id);
					}
				}
				return new ResultBean<>(cs.getId());
			}else {
				return new ResultBean<>(new MyException("添加异常"));
			}
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new ResultBean<>(new MyException("系统异常"));
		}
	}

	@Override
	public ResultBean<List<Map<String, Object>>> selectByTeacherId(int userId) {
		// TODO Auto-generated method stub
		try {
			List<Map<String, Object>> list=dao.selectByTeacherId(userId);
			return new ResultBean<>(list);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new ResultBean<>(e);
		}
	}

	@Override
	public ResultBean<List<Map<String, Object>>> selectBySchoolId(int schoolId,int pageIndex,int size) {
		// TODO Auto-generated method stub
		try {
			List<Map<String, Object>> list=dao.selectBySchoolId(schoolId,(pageIndex-1)*size,size);
			return new ResultBean<>(list);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new ResultBean<>(e);
		}
	}

	@Override
	public ResultBean<Map<String, Object>> selectById(int id,int userid) {
		// TODO Auto-generated method stub
		try {
			Map<String, Object> map=new HashMap<>();
			CourseSeeing cs=dao.selectById(id);
			List<CourseSimple> list=csDao.selectList(new EntityWrapper<CourseSimple>().eq("courseid", id).and().eq("coursetype", 1));
			map.put("CourseSeeing", cs);
			map.put("CourseSimple", list);
			int count=cDao.selectCount(new EntityWrapper<Collect>().eq("collectid", id).and().eq("userid", userid).and().eq("collecttype", 5));
			if(count>0) {
				map.put("isCollect", true);
			}else {
				map.put("isCollect", false);
			}
			int num=oDao.selectCount(new EntityWrapper<CourseOrder>().eq("courseid", cs.getId()).and().eq("coursetype", 1));
			map.put("pinNum", num);
			Language lang=lDao.selectById(cs.getLanguageid());
			map.put("language", lang);
			User user=uDao.selectById(cs.getUserid());
			map.put("user", user);
			return new ResultBean<>(map);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new ResultBean<>(e);
		}
	}

	@Override
	public ResultBean<List<Map<String, Object>>> getList(CourseSeeing cs,String hours, String prices, Integer days, int score, String keyWord,
			int pageIndex,int size) {
		// TODO Auto-generated method stub
		StringBuffer whereSql=new StringBuffer(" and name like '%"+keyWord+"%' ");
		if(cs.getLanguageid()!=null&&cs.getLanguageid()!=0) {
			whereSql.append(" and languageid="+cs.getLanguageid());
		}
		if(cs.getStageid()!=null&&cs.getStageid()!=0) {
			whereSql.append(" and stageid="+cs.getStageid());
		}
		if(hours!=null&&!hours.equals("")) {
			String[] hour=hours.split("-");
			whereSql.append(" and hour>="+hour[0]+" and hour<="+hour[1]);
		}
		if(prices!=null&&!prices.equals("")) {
			String[] price=prices.split("-");
			whereSql.append(" and totalprice>="+price[0]+" and totalprice<="+price[1]);
		}
		if(days!=null&&days!=0&&days!=5) {        //时间段怎么算
			//whereSql.append(" and t.languagegrade='"+tea.getLanguagegrade()+"'");
			if(days==1) {
				whereSql.append(" and time>='"+DataUtil.CalendarTime(-3)+" 23:59:59'");
			}else if(days==2) {
				whereSql.append(" and time between '"+DataUtil.CalendarTime(-3)+" 00:00:00'  and '"+DataUtil.CalendarTime(-7)+" 23:59:59'");
			}else if(days==3){
				whereSql.append(" and time between '"+DataUtil.CalendarTime(-7)+" 00:00:00'  and '"+DataUtil.CalendarTime(-15)+" 23:59:59'");
			}else if(days==4) {
				whereSql.append(" and time between '"+DataUtil.CalendarTime(-15)+" 00:00:00'  and '"+DataUtil.CalendarTime(-30)+" 23:59:59'");
			}else if(days==5) {
				whereSql.append(" and time>='"+DataUtil.CalendarTime(-30)+" 00:00:00'");
			}
		}
		if(cs.getSources()!=null&&!cs.getSources().equals("")) {
			whereSql.append(" and sources ='"+cs.getSources()+"'");
		}
		if(cs.getIsspelling()!=null) {
			whereSql.append(" and isspelling='"+cs.getIsspelling()+"'");
		}
		whereSql.append(" and states=2");
		String orderStr="";
		if(score==3) {    //价格
			orderStr=" order by totalprice";
		}else if(score==1) {
			orderStr=" order by time desc";
		}
		try {
			List<Map<String, Object>> list=dao.getList(whereSql.toString(), orderStr,(pageIndex-1)*size,size);
			List<Map<String, Object>> list1=new ArrayList<>();
			for(Map<String, Object> map:list) {
				Integer courseId=Integer.valueOf(map.get("id").toString());
				Double fen=tDao.selectAvgScoreByeacherId(courseId, 1);
				if(fen==null) {
					fen=0.0;
				}
				map.put("fen", fen);
				list1.add(map);
			}
			if(score==2) {
				 Collections.sort(list1, new Comparator<Map<String, Object>>() {
			            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
			                Double name1 = Double.valueOf(o1.get("fen").toString()) ;//name1是从你list里面拿出来的一个 
			                Double name2 = Double.valueOf(o2.get("fen").toString()) ; //name1是从你list里面拿出来的第二个name
			                return name1.compareTo(name2);
			            }
			        });
			}
			return new ResultBean<>(list1);
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new ResultBean<>(e);
		}
	}

	@Override
	public ResultBean<List<Map<String, Object>>> getSpellingList(int pageIndex,int size,String keyWord) {
		// TODO Auto-generated method stub
		try {
			List<Map<String, Object>> list=dao.selectInIds((pageIndex-1)*size,size,keyWord);
			for(Map<String, Object> map:list) {
				Integer courseid=Integer.parseInt(map.get("id").toString());
				int pinNum=oDao.getCountByCourseid(courseid);
				map.put("pinNum", pinNum);
			}
			return new ResultBean<>(list);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new ResultBean<>(e);
		}
	}

	@Override
	public ResultBean<Integer> getListCount(CourseSeeing cs, String hours, String prices, Integer days,
			String keyWord) {
		// TODO Auto-generated method stub
		StringBuffer whereSql=new StringBuffer(" and name like '%"+keyWord+"%' ");
		if(cs.getLanguageid()!=null&&cs.getLanguageid()!=0) {
			whereSql.append(" and languageid="+cs.getLanguageid());
		}
		if(cs.getStageid()!=null&&cs.getStageid()!=0) {
			whereSql.append(" and stageid="+cs.getStageid());
		}
		if(hours!=null&&!hours.equals("")) {
			String[] hour=hours.split("-");
			whereSql.append(" and hour>="+hour[0]+" and hour<="+hour[1]);
		}
		if(prices!=null&&!prices.equals("")) {
			String[] price=prices.split("-");
			whereSql.append(" and totalprice>="+price[0]+" and totalprice<="+price[1]);
		}
		
		if(cs.getSources()!=null&&!cs.getSources().equals("")) {
			whereSql.append(" and sources ='"+cs.getSources()+"'");
		}
		if(cs.getIsspelling()!=null) {
			whereSql.append(" and isspelling='"+cs.getIsspelling()+"'");
		}
		whereSql.append(" and states=2");
		int count=dao.getListCount(whereSql.toString());
		return new ResultBean<Integer>(count);
	}

	@Override
	public ResultBean<Integer> selectBySchoolIdCount(int schoolId) {
		// TODO Auto-generated method stub
		try {
			List<Map<String, Object>> list=dao.selectBySchoolIdCount(schoolId);
			return new ResultBean<>(list.size());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new ResultBean<>(e);
		}
	}

	@Override
	public ResultBean<Integer> getSpellingListCount() {
		// TODO Auto-generated method stub
		try {
			int list=dao.selectInIdsCount();
			return new ResultBean<>(list);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new ResultBean<>(e);
		}
	}

}
